﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business.Util;
using ZLCMS.Data.Model;
using DotNet.Common.NHibernateUtil.QueryFilter;
using NHibernate;
using System.IO;
using Ionic.Zip;
using NHibernate.Hql.Util;

namespace ZLCMS.Web.SystemManage.Basics.Shop.Coupon
{
    public partial class CouponTicketList : System.Web.UI.Page
    {
        protected ZLCMS.Business.DwzFrame.FrameHelper _framePage;

        protected void Page_Load(object sender, EventArgs e)
        {
            _framePage = new ZLCMS.Business.DwzFrame.FrameHelper(this);

            //设置分页大小
            int pageSize = _framePage.IsAjaxPagerPostBack ? _framePage.PageSize : 20;

            //设置页码
            int pageIndex = _framePage.IsAjaxPagerPostBack ? _framePage.PageIndex : 1;
            int onlineFlag = 1;

            QueryFilterList filters = new QueryFilterList();

            if (!string.IsNullOrEmpty(Request["code"]))
            {
                filters.Add(new StringFilter("TicketCode", "%" + Request["code"] + "%", StringCompairType.Like));
            }
            if (!string.IsNullOrEmpty(Request["member"]))
            {
                filters.Add(new StringFilter("MemberAccount", "%" + Request["member"] + "%", StringCompairType.Like));
            }
            if (!string.IsNullOrEmpty(Request["ruleid"]))
            {
                filters.Add(new NumberFilter("RuleId", Int32.Parse(Request["ruleid"])));
            }
            if (!string.IsNullOrEmpty(Request["status"]) && Request["status"] != "-1")
            {
                filters.Add(new StringFilter("Status", Request["status"]));
            }
            if (!string.IsNullOrEmpty(Request["pattern"]) && Request["pattern"] == "offline")
            {
                onlineFlag = 0;
            }
            filters.Add(new NumberFilter("OnlineFlag", onlineFlag));
            filters.Add(new StringFilter("CouponType", "coupon"));

            string hql = "from ShopCouponTicket where 1=1 ";

            foreach (DataFilter filter in filters)
            {
                hql += " and " + filter.GetSection();
            }

            using (NHibernate.ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                IQuery query = session.CreateQuery("select count(*) " + hql);
                filters.SetUp(query);
                //设置记录总数
                _framePage.RecordCount = Convert.ToInt32(query.UniqueResult());

                if (!string.IsNullOrEmpty(Request["exportexcel"]))
                {
                    query = session.CreateQuery(hql );
                    filters.SetUp(query);
                    IList<ShopCouponTicket> ticketList = query.List<ShopCouponTicket>();
                    StringWriter sw = new StringWriter();

                    sw.WriteLine("优惠券编号\t标题\t密码\t额度\t创建时间\t开始时间\t结束时间\t使用最低限度");
                    foreach (ShopCouponTicket item in ticketList)
                    {
                        sw.WriteLine(
                               item.TicketCode + "\t"
                            + item.Title + "\t"
                            + item.Amount + "\t"
                            + item.CreateDate + "\t"
                             + item.StartUseDate + "\t"
                             + item.EndUseDate + "\t"
                             + item.OrderMinAmount + "\t");
                        item.Status = "2";
                        session.Update(item);
                    }
                    sw.Close();
                    session.Flush();

                    OutputKit.OutputExcel(Response, sw);
                }
                else if (!string.IsNullOrEmpty(Request["downloadfile"]))
                {
                    query = session.CreateQuery(hql );
                    filters.SetUp(query);
                    IList<ShopCouponTicket> ticketList = query.List<ShopCouponTicket>();
                    string fileName = "";
                    using (ZipFile zip = new ZipFile())
                    {
                        foreach (ShopCouponTicket item in ticketList)
                        {
                            //将文件加入压缩包
                            fileName = item.Title;
                            zip.AddFile(ServerUtil.GetRootPath() + item.QrcodeUrl,"/");
                        }
                        zip.Save(ServerUtil.GetRootPath() + "/upload/qrcode/" + fileName+".zip");
                    }
                    DownloadFunc("/upload/qrcode/" + fileName+".zip", fileName);
                }
                else
                {
                    query = session.CreateQuery(hql);
                    filters.SetUp(query);
                    filters.SetPager(query, pageIndex, pageSize);

                    //设置数据源
                    repeater1.DataSource = query.List<ShopCouponTicket>();
                    repeater1.DataBind();
                }
            }
        }

        public void DownloadFunc(string filepath, string fileName)
        {
            System.IO.Stream iStream = null;

            byte[] buffer = new Byte[10240];

            int length;

            long dataToRead;

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (!filepath.ToLower().Contains("/upload/qrcode/"))
                    {
                        Response.Write("<script>alert('禁止访问')</script>");
                        iStream.Close();
                        Response.End();
                    }
                    filepath = Server.MapPath("~/" + filepath);

                    iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                        System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    Response.Clear();

                    dataToRead = iStream.Length;

                    long p = 0;
                    if (Request.Headers["Range"] != null)
                    {
                        Response.StatusCode = 206;
                        p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
                    }
                    if (p != 0)
                    {
                        Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
                    }
                    Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(fileName + ".zip")));

                    iStream.Position = p;
                    dataToRead = dataToRead - p;

                    while (dataToRead > 0)
                    {
                        if (Response.IsClientConnected)
                        {
                            length = iStream.Read(buffer, 0, 10240);

                            Response.OutputStream.Write(buffer, 0, length);
                            Response.Flush();

                            buffer = new Byte[10240];
                            dataToRead = dataToRead - length;
                        }
                        else
                        {
                            dataToRead = -1;
                        }
                    }
                }
                catch
                {
                    Response.Write("<script>alert('文件不存在')</script>");
                    if (iStream != null)
                    {
                        iStream.Close();
                    }
                }
            }
        }
    }
}